package projetstackoverflow

import java.nio.file.attribute.UserDefinedFileAttributeView;

import org.springframework.dao.DataIntegrityViolationException

class AuthorController {

    
	static scaffold = true
	
	def login = {
		session.lastUri = params.lastUri
	}
	
	def doLogin = {
		def author = Author.findWhere(pseudo:params['pseudo'], password:params['password'])
		def targetUri = session.lastUri ?: "/"
		if (author)
		{
			session.author = author
			redirect(uri: targetUri)
		}
		else
		{
			redirect(controller:'author', action:'login', params:['lastUri':session.lastUri])
		}
		
		
		
	}
	
	def doLogout = {
		
		//def user = User.findWhere(email:params['email'], password:params['password'])
		def author = session.author
		session.author = null
	  	
		def targetUri = params.lastUri ?: "/"
		redirect(uri: targetUri)
		/*if (author)
		{
			
		}
		else
		{
		  
		}*/
	}
	
	def changeLocale(String baseLocale, String localeExtension, String lastUri) {
		session['org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'] = new Locale(baseLocale, localeExtension)
		def targetUri = lastUri ?: "/"
	  	redirect(uri: targetUri)
	}
	
	
	def save() {
        def authorInstance = new Author(params)
		
		if(!authorInstance.registrationDate)
			authorInstance.registrationDate = new Date()
			
		authorInstance.admin = false 
        if (!authorInstance.save(flush: true)) {
            render(view: "create", model: [authorInstance: authorInstance])
            return
        }

        redirect(action: "show", id: authorInstance.id)
    }
	
	def list(Integer max) {
		params.max = 10
		params.sort = params.sort ?: "registrationDate"
		params.order = params.order ?: "desc"
		def authorInstanceList =  Author.list(params)
		def total =  Author.count()
		
		[authorInstanceList:authorInstanceList, authorInstanceTotal: total]
	}
	
	 def delete(Long id) {
		 //Author never deleted
	 }
	 
	 def edit(Long id) {
		 def authorInstance = Author.get(id)
		 if (!authorInstance) {
			 redirect(action: "list")
			 return
		 }
		 if(!(session.author.admin || session.author.id == authorInstance.id))
		 {
			 redirect(action:'list')
		 }
		 [authorInstance: authorInstance]
	 }
}
